package com.jic.point.controller.feign;

import com.jic.common.base.vo.RestResult;
import com.jic.point.api.HaierConsumePointApi;
import com.jic.point.model.entity.*;
import com.jic.point.rest.request.ChannelConsume;
import com.jic.point.rest.request.SignData;
import com.jic.point.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * @description: TODO
 * @author: lixuehui
 * @date: 2020/12/9 18:30
 * @Version 1.0
 */
@Api(tags = {"积分消耗接口"})
@RequestMapping(value = "/api/point")
@RestController
public class HaierConsumePointFeign implements HaierConsumePointApi {
    @Resource
    private HaierSmartHomePointService haierSmartHomePointService;

    @Resource//第三方机构
    private ConfThirdPartService confThirdPartService;
    @Resource//平台
    private ConfPlatformService confPlatformService;
    @Resource//部门
    private ConfBdService confBdService;
    @Resource//供应闪
    private ConfSupplierService confSupplierService;
    @Resource//活动规则
    private ConfActivityRuleService confActivityRuleService;
    @Resource//会员台账表
    PublMemberBalanceService balanceService;
    @Resource//会员
    PublMemberLogService publMemberLogService;

    /**
     * @Auther: lixuehui
     * @DATE: 2020/11/13
     * 单渠道消耗服务 --提供验签通过的平台方
     * 接口中需要的key和secret由积分中心授权下发。
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("getPointConsume")
    @ApiOperation(value = " 单渠道消耗服务")
    public RestResult<?> getPointConsume(ChannelConsume channelConsume) {
        SignData signData = new SignData();
        BeanUtils.copyProperties(channelConsume, signData);
        //第一层校验
        RestResult restResult = checkPointsReceive(signData);
        if (restResult != null) return restResult;
        //第二层校验
        RestResult restResult1 = checkPointsReceive2(signData);
        if (restResult1 != null) return restResult1;
        //进行积分增加减少操作
        //第三方平台消耗积分
        if ("THRID_PART_PLATFORM".equals(signData.getBusiType())) {



        }
        //平台消耗积分
        if ("PLATFORM".equals(signData.getBusiType())) {

        }
        //供应商消耗积分
        if ("SUPPLY".equals(signData.getBusiType())) {

        }
        //用户消耗积分
        if ("MEMBER".equals(signData.getBusiType())) {
            PublMemberBalance balance = new PublMemberBalance();
            balance.setMemberCode(channelConsume.getBusiCode());
            balance.setDeleteFlag(0);
            //消耗积分
            int flag = balanceService.consumePoint(balance);
            //向台账log表里插一条记录
            PublMemberLog publMemberLog = new PublMemberLog();
            publMemberLog.setMemberCode(balance.getMemberCode());
            publMemberLog.setThirdUserId(balance.getThirdUserId());
            publMemberLog.setAmount(balance.getTotal());
            int flag1 = publMemberLogService.insertSelective(publMemberLog);
            if(flag < 1 || flag1 <1) TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//有一条不正确 回滚！
        }
        return RestResult.success("成功消耗积分！");
    }
    /**
     * @param channelConsume
     * @return
     * @Auther: lixuehui
     * @DATE: 2020/11/13
     * . 不分渠道消耗服务 --消耗用户的有效积分，不区分积分来源渠道
     * 接口中需要的key和secret由积分中心授权下发。
     */
    @Override
    public RestResult<?> getNotChannelConsume(ChannelConsume channelConsume) {
        //1、所有的调用需要校验，是否在【conf_api_authority_apply】有配置调用api授权；
        SignData signData = new SignData();
        signData.setBusiType(channelConsume.getBusiType());
        signData.setBusiType(channelConsume.getBusiCode());
        //第一层校验
        RestResult restResult = checkPointsReceive(signData);
        if (restResult != null) return restResult;
        return RestResult.success("ok");
    }
    //积分消耗 第二层校验
    public RestResult checkPointsReceive2(SignData signData) {
        //  `sts` int(2) DEFAULT '0' COMMENT '状态（-3、双向冻结；-2、流入冻结，流出正常，-1、停用，0、初始化；1、启用；2、流入正常，流出冻结；）',
        //第三方机构校验
        if ("THRID_PART_PLATFORM".equals(signData.getBusiType())) {
            List<ConfThirdPart> confThirdParts = confThirdPartService.selThirdPartByCode(signData);
            if (confThirdParts.size() < 1) return RestResult.error("0011", "第三方机构编码有误或不存在！");
            ConfThirdPart confThirdPart = confThirdParts.get(0);
            if (confThirdPart.getSts() == -3) return RestResult.error("0012", "当前第三方机构，状态有误");
            if (confThirdPart.getAuditFlag() == 0) return RestResult.error("0013", "当前第三方机构，未启用");
            if (confThirdPart.getAuditSts() != 1) return RestResult.error("0014", "当前第三方机构，未审核通过");
        }
        //平台校验
        if ("PLATFORM".equals(signData.getBusiType())) {
            List<ConfPlatform> confPlatforms = confPlatformService.selectByPrimaryCode(signData);
            if (confPlatforms.size() < 1) return RestResult.error("0011", "平台编码有误或不存在！");
            ConfPlatform confPlatform = confPlatforms.get(0);
            if (confPlatform.getSts() == -3) return RestResult.error("0012", "当前平台，状态有误");
            if (confPlatform.getAuditFlag() == 0) return RestResult.error("0013", "当前平台，未启用");
            if (confPlatform.getAuditSts() != 1) return RestResult.error("0014", "当前平台，未审核通过");
            List<ConfBdPlatfromRela> platfromRela = confPlatformService.getPlatfromRela(confPlatform);
            if (platfromRela.size() < 1) return RestResult.error("0015", "当前平台编码未绑定唯一结算部门！");
        }
        //部门校验
        if ("DEPARTMENT".equals(signData.getBusiType())) {
            List<ConfBd> confBds = confBdService.selConfBdByCode(signData);
            if (confBds.size() < 1) return RestResult.error("0011", "部门编码有误或不存在！");
            ConfBd confBd = confBds.get(0);
            if (confBd.getSts() == -3) return RestResult.error("0012", "当前部门，状态有误");
            if (confBd.getAuditSts() != 1) return RestResult.error("0014", "当前部门，未审核通过");
        }
        //供应商
        if ("SUPPLY".equals(signData.getBusiType())) {
            List<ConfSupplier> confSuppliers = confSupplierService.selConfSupplierByCode(signData);
            if (confSuppliers.size() < 1) return RestResult.error("0011", "供应商编码有误或不存在！");
            ConfSupplier confSupplier = confSuppliers.get(0);
            if (confSupplier.getSts() == -3) return RestResult.error("0012", "当前供应商，状态有误");
            if (confSupplier.getAuditSts() != 1) return RestResult.error("0014", "当前供应商，未审核通过");
        }
        //活动规则
        if ("ACTIVITY_RULE".equals(signData.getBusiType())) {
            List<ConfActivityRule> confActivityRules = confActivityRuleService.selConfActivityRuleByCode(signData);
            if (confActivityRules.size() < 1) return RestResult.error("0011", "活动规则编码有误或活动规则不存在！");
            ConfActivityRule confActivityRule = confActivityRules.get(0);
            if (confActivityRule.getSts() == -3) return RestResult.error("0012", "当前活动规则，状态有误");
            if (confActivityRule.getAuditSts() != 1) return RestResult.error("0014", "当前活动规则，未审核通过");
        }
        //会员台账表
        if ("MEMBER".equals(signData.getBusiType())) {
            List<PublMemberBalance> publMembers = balanceService.queryPublMemberBalanceByCode(signData);
            if (publMembers.size() < 1) return RestResult.error("0011", "用户规则编码有误或用户规则不存在！");
            PublMemberBalance balance = publMembers.get(0);
            int total = balance.getTotal().compareTo(BigDecimal.ZERO);
            int available = balance.getAvailable().compareTo(BigDecimal.ZERO);
            if(total == -1 || available == -1) return RestResult.error("0022", "用户可用积分或者总积分小于0，不能进行消耗!");
        }
        return null;
    }

    //积分消耗  校验主体  第一层校验
    public RestResult checkPointsReceive(SignData signData) {
        //查询参数业务类型和编码是否为空
        if (signData.getBusiType() != null && "".equals(signData.getBusiType()) && signData.getBusiCode() != null) return RestResult.error("0001", "业务类型或业务类型对应编码不能为空");
        //通过业务类型查询数据
        List<SignData> signData1 = haierSmartHomePointService.selAuthorityList(signData);
        if (signData1.size() < 1) return RestResult.error("0002", "当前操作，业务类型以及编码不存在");
        SignData sign = signData1.get(0);
        if (sign.getStatus() != 2) return RestResult.error("0003", "当前操作，渠道未启用！请先启用");
        if (sign.getAppKey() != null && sign.getSecreKey() != null) return RestResult.error("0004", "标识码和秘钥为空或不匹配");
        //判断是否有消耗操作权限
        if (sign.getConsumptionType() != 1) return RestResult.error("0005", "当前消耗操作，无权限进行消耗积分的操作！");
        return null;
    }
}
